//
//  YWTroubleMissionDBManager.m
//  maintain
//
//  Created by 烟雨云渊 on 17/3/7.
//  Copyright © 2017年 ewin. All rights reserved.
//

#import "YWTroubleMissionDBManager.h"
#import "YWDBTool.h"
#import "YWReportTroubleManager.h"
#import "YWReportTroubleDBManager.h"

#import "YWTroubleMissionModel.h"
#import "YWReportTroubleModel.h"
#import "YWLoginUser.h"
#import "YWLoginTool.h"
#import "YWCommonTool.h"

@implementation YWTroubleMissionDBManager
YWSingletonM(Manager)
- (FMDatabase*)fmdb{
    return [[YWDBTool shareDBTool] fmdb];
}
- (FMDatabaseQueue*)dbQeue{
    return [[YWDBTool shareDBTool] dbQeue];
}

#pragma mark - 创建维修任务表
- (BOOL)createTroubleMissionApiTable{
    NSString * sql = @"CREATE TABLE IF NOT EXISTS 'YW_TroubleMission' (troubleId integer,executorId integer,creatorId integer,demand varchar,cutoffTime timestamp,missionType integer,rejectReason varchar,troubleStatus integer,createTime timestamp,updateTime timestamp,status integer,read boolean DEFAULT 0,uploadFail boolean DEFAULT 0)";
    return [[self fmdb] executeUpdate:sql];
}

- (BOOL)updateTroubleMissionWithArray:(NSArray*)troubleMissionArray needUpdateReportTrouble:(BOOL)need{
    if (troubleMissionArray.count == 0) {
        return YES;
    }
    __block NSMutableArray * reportTroubleArray = [NSMutableArray array];
    __block BOOL executeResult = YES;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [troubleMissionArray enumerateObjectsUsingBlock:^(YWTroubleMissionModelApiJson*  _Nonnull troubleMission, NSUInteger idx, BOOL * _Nonnull stop) {
            //更新报障
            if (troubleMission.trouble && need) {
                [reportTroubleArray addObject:troubleMission.trouble];
            }
            
            //read，uploadFailed创建时有默认值，在这里不更新
            sql = @"SELECT * FROM 'YW_TroubleMission' WHERE troubleId=?;";
            FMResultSet* set = [db executeQuery:sql, @(troubleMission.trouble.troubleId)];
            if ([set next]) {
                sql = @"UPDATE 'YW_TroubleMission' SET executorId =?,creatorId =?,demand =?,cutoffTime =?,missionType =?,rejectReason =?,troubleStatus =?, createTime=?,updateTime =?,status =? WHERE troubleId =?;";
                executeResult = [db executeUpdate:sql,@(troubleMission.executor.uniqueId),@(troubleMission.creator.uniqueId),troubleMission.demand,@(troubleMission.cutoffTime),@(troubleMission.missionType),troubleMission.rejectReason,@(troubleMission.troubleStatus),@(troubleMission.createTime),@(troubleMission.updateTime),@(troubleMission.status),@(troubleMission.trouble.troubleId)];
            }
            else {
                sql = @"INSERT INTO 'YW_TroubleMission' (troubleId,executorId,creatorId,demand,cutoffTime,missionType,rejectReason,troubleStatus,createTime,updateTime,status) VALUES (?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?);";
                executeResult = [db executeUpdate:sql,@(troubleMission.trouble.troubleId),@(troubleMission.executor.uniqueId),@(troubleMission.creator.uniqueId),troubleMission.demand,@(troubleMission.cutoffTime),@(troubleMission.missionType),troubleMission.rejectReason,@(troubleMission.troubleStatus),@(troubleMission.createTime),@(troubleMission.updateTime),@(troubleMission.status)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
    [[YWReportTroubleManager shareManager] updateReportTroubleWithArray:reportTroubleArray];
    return executeResult;
}

- (BOOL)setUploadFailWithTroubleMissionModel:(YWTroubleMissionModel*)troubleMission{
    __block BOOL executeResult = YES;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        sql = @"UPDATE 'YW_TroubleMission' SET uploadFail=? WHERE troubleId=?;";
        executeResult = [db executeUpdate:sql, @(troubleMission.uploadFail), @(troubleMission.trouble.troubleId)];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (NSArray*)troubleMissionModelWithStatus:(YWTroubleMissionStatus)status page:(NSInteger)page{
    if (page==0) {
        return nil;
    }
    __block NSMutableArray* missionArray = [NSMutableArray array];
    __block NSInteger showCount = page * 10;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        YWLoginUser *currentUser = [YWLoginTool loginUser];
        //取维修任务
        NSString* sql = nil;//完成和未完成排序时间不一样
        if (status == YWTroubleMissionStatusFinish) {
//            sql = [NSString stringWithFormat:@"SELECT * FROM 'YW_TroubleMission' WHERE troubleStatus = %lu AND (executorId = %lu or observerIds like '%%%lu%%') ORDER BY updateTime DESC LIMIT %lu",(unsigned long)status,(long)currentUser.uniqueId,(long)currentUser.uniqueId, (long)showCount];
            sql = [NSString stringWithFormat:@"SELECT * FROM 'YW_TroubleMission' WHERE troubleStatus = %lu AND (executorId = %lu or troubleId in (SELECT troubleId FROM 'YW_reportTrouble' WHERE observerIds like '%%%lu%%')) ORDER BY updateTime DESC LIMIT %lu",(unsigned long)status,(long)currentUser.uniqueId,(long)currentUser.uniqueId, (long)showCount];
        }else{
//            sql = [NSString stringWithFormat:@"SELECT * FROM 'YW_TroubleMission' WHERE troubleStatus = %lu AND (executorId = %lu or observerIds like '%%%lu%%') ORDER BY createTime DESC LIMIT %lu",(unsigned long)status,(long)currentUser.uniqueId,(long)currentUser.uniqueId, (long)showCount];
            sql = [NSString stringWithFormat:@"SELECT * FROM 'YW_TroubleMission' WHERE troubleStatus = %lu AND (executorId = %lu or troubleId in (SELECT troubleId FROM 'YW_reportTrouble' WHERE observerIds like '%%%lu%%')) ORDER BY createTime DESC LIMIT %lu",(unsigned long)status,(long)currentUser.uniqueId,(long)currentUser.uniqueId, (long)showCount];
        }
        FMResultSet* set = [db executeQuery:sql];
        NSString *lastDate = nil;
        NSMutableArray *array = nil;
        while ([set next]) {
            YWTroubleMissionModel* troubleMission = [self troubleMissionModelWithFMResultSet:set FMDatabase:db needSelectReportTrouble:YES];
            NSString *timeDate = nil;
            if (status == YWTroubleMissionStatusFinish) {
                timeDate = [YWCommonTool showChineseFormatterDate:troubleMission.updateTime/1000];
            }else{
                timeDate = [YWCommonTool showChineseFormatterDate:troubleMission.createTime/1000];
            }
            if (lastDate==nil || ![timeDate isEqualToString:lastDate]) {
                lastDate = timeDate;
                array = [NSMutableArray array];
            }
            [array addObject:troubleMission];
            if (![missionArray containsObject:array] && array.count) {
                [missionArray addObject:array];
            }
        }
        [db closeOpenResultSets];
    }];
    return missionArray.count ? missionArray : nil;
}


- (NSString*)allUnfinishTroubleMissionIds{
    NSMutableString *troubelIds = [NSMutableString string];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT troubleId FROM 'YW_TroubleMission' WHERE troubleStatus=?";
        FMResultSet* set = [db executeQuery:sql,@(YWTroubleMissionStatusAssign)];
        while ([set next]) {
            NSInteger troubelId = [set intForColumn:@"troubleId"];
            if (troubelId>0) {
                [troubelIds appendString:[@(troubelId) stringValue]];
                [troubelIds appendString:@","];
            }
        }
        [db closeOpenResultSets];
    }];
    return [NSString stringWithFormat:@"%@",troubelIds];
}

- (YWTroubleMissionModel*)troubleMissionModelWithTroubleId:(NSInteger)troubleId{
    __block YWTroubleMissionModel* troubleMission = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'YW_TroubleMission' WHERE troubleId = ?";
        FMResultSet* set = [db executeQuery:sql, @(troubleId)];
        if ([set next]) {
            troubleMission = [self troubleMissionModelWithFMResultSet:set FMDatabase:db needSelectReportTrouble:YES];
        }
        [db closeOpenResultSets];
    }];
    return troubleMission;
}

- (YWTroubleMissionModel*)troubleMissionModelWithFMResultSet:(FMResultSet*)set FMDatabase:(FMDatabase*)db needSelectReportTrouble:(BOOL)need
{
    YWTroubleMissionModel * troubleMission = [[YWTroubleMissionModel alloc] init];
    NSInteger troubleId = [set intForColumn:@"troubleId"];
    if (need) {
        NSString* troubleSql = @"SELECT * FROM 'YW_ReportTrouble' WHERE troubleId = ?;";
        FMResultSet *troubleSet = [db executeQuery:troubleSql, @(troubleId)];
        if ([troubleSet next]) {
            troubleMission.trouble = [[YWReportTroubleDBManager shareManager] reportTroubleWithFMResultSet:troubleSet FMDatabase:db needSelectTroubleMission:NO];
        }else{
            YWReportTroubleModel * reportTrouble = [[YWReportTroubleModel alloc] init];
            reportTrouble.troubleId = troubleId;
            troubleMission.trouble = reportTrouble;
        }
    }
    
    NSInteger executorId = [set intForColumn:@"executorId"];
    NSInteger creatorId = [set intForColumn:@"creatorId"];
    NSString* userSql = @"SELECT * FROM 'handler' WHERE uniqueId = ?;";
    FMResultSet *userSet = [db executeQuery:userSql, @(executorId)];
    if ([userSet next]) {
        troubleMission.executor = [[YWDBTool shareDBTool] handlerWithSet:userSet];
    }
    userSet = [db executeQuery:userSql, @(creatorId)];
    if ([userSet next]) {
        troubleMission.creator =  [[YWDBTool shareDBTool] handlerWithSet:userSet];
    }

    troubleMission.demand = [set stringForColumn:@"demand"];
    troubleMission.cutoffTime = [set longLongIntForColumn:@"cutoffTime"];
    troubleMission.missionType = [set intForColumn:@"missionType"];
    troubleMission.rejectReason = [set stringForColumn:@"rejectReason"];
    troubleMission.troubleStatus = [set intForColumn:@"troubleStatus"];
    troubleMission.createTime = [set longLongIntForColumn:@"createTime"];
    troubleMission.updateTime = [set longLongIntForColumn:@"updateTime"];
    troubleMission.status = [set intForColumn:@"status"];
    //观察者
//    NSMutableArray *observer = [NSMutableArray array];
//    NSString *observerSql = [NSString stringWithFormat:@"SELECT * FROM 'handler' WHERE uniqueId in (%@)",troubleMission.observerIds];
//    FMResultSet *observerSet = [db executeQuery:observerSql];
//    while ([observerSet next]) {
//        YWHandler *handler = [[YWDBTool shareDBTool] handlerWithSet:observerSet];
//        [observer addObject:handler];
//    }
//    troubleMission.observers = observer;
  
    return troubleMission;
}

- (NSArray*)uploadFailTroubleMissionArray{
    __block NSMutableArray* uploadFailTroubleMissionArray = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        sql = [NSString stringWithFormat:@"SELECT * FROM 'YW_TroubleMission' WHERE uploadFail = 1"];
        FMResultSet* newset = [db executeQuery:sql];
        while ([newset next]) {
          YWTroubleMissionModel* troubleMission = [self troubleMissionModelWithFMResultSet:newset FMDatabase:db needSelectReportTrouble:YES];
        [uploadFailTroubleMissionArray addObject:troubleMission];
        }
        [db closeOpenResultSets];
    }];
    return uploadFailTroubleMissionArray.count?uploadFailTroubleMissionArray:nil;
}

-(BOOL)updateTroubleMissionStatus:(NSInteger)status troubleId:(NSInteger)troubleId{
    __block BOOL executeResult = YES;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"UPDATE 'YW_TroubleMission' SET troubleStatus=? WHERE troubleId=?;";
        executeResult = [db executeUpdate:sql, @(status), @(troubleId)];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

@end
